import {Table, Modal, message, Form, Input, Button, Select, Image, Upload, UploadFile, UploadProps} from 'antd';
import type {ColumnsType} from 'antd/es/table';
import React, {useEffect, useState} from 'react';
import {
    DeleteTwoTone,
    EditTwoTone,
    ExclamationCircleOutlined, PlusOutlined,
    SearchOutlined,
    SnippetsTwoTone
} from "@ant-design/icons";
import {
    delAccount,
    delAllAccount, editAccount,
    getAccountDetails,
    getAccountList,
    getAccountSearch
} from "../../api/AllAccount/accountApi.ts";
import publicStyle from "../../assets/css/public.module.css";
import style from '../../assets/css/AllAccount/accManage.module.css'
import {getBase64, MODAL_WIDTH, phoneRules, purviewRules, temporaryRules} from "../../utils/publicStyleAndRules.ts";
import {RcFile} from "antd/es/upload";


const {confirm} = Modal;

interface DataType {
    key: React.Key;
    id: number,
    account: string;
    purview: string;
    name: string;
    sex: string;
    phone: string;
    head:string
}

const options: object[] = [
    {label: '医务管理员', value: '医务管理员'},
    {label: '医生', value: '医生'},
    {label: '护士', value: '护士'},
    {label: '实习助理', value: '实习助理'},
    {label: '药房', value: '药房'}
]

const formItemLayout = {
    labelCol: {span: 3},
};
export default function AccManage() {

    // 表格列
    const columns: ColumnsType<DataType> = [
        {title: '帐号', dataIndex: 'account', key: 'account',},
        {title: '权限', dataIndex: 'purview', key: 'purview',},
        {title: '姓名', dataIndex: 'name', key: 'name',},
        {title: '性别', dataIndex: 'sex', key: 'sex',},
        {title: '手机号', dataIndex: 'phone', key: 'phone',},
        {
            title: '账号操作', key: Date.now().toString(),
            render: (_, record) =>
                <div className={style.operation}>
                    <SnippetsTwoTone className={style.btn} onClick={() => showModal(record.id, false)}/>
                    <DeleteTwoTone className={style.btn} onClick={() => handleDelClick([record.id], 'single')}/>
                    <EditTwoTone className={style.btn} onClick={() => showModal(record.id, true)}/>
                </div>,
        },
    ];

    // 查询表单
    const [dataForm] = Form.useForm();

    // 详情表单
    const [infoForm] = Form.useForm();

    // 选中的表格行id
    const [selectIds, setIds] = useState<number[]>([]);

    // 是否编辑
    const [isEdit, setIsEdit] = useState<boolean>(true);

    // module显隐
    const [isModalOpen, setIsModalOpen] = useState<boolean>(false);

    // 复选框操作
    const rowSelection = {
        onChange: (selectedRowKeys: React.Key[]) => {
            setIds(selectedRowKeys);
        },
    };

    // 表格数据
    const [data, setData] = useState<DataType[]>([]);

    // 表格分页
    const [pagination, setPagination] = useState({
        page: 1,
        size: 10,
        total: 0,
    });

    // 处理账号删除
    const handleDelAccount = async (id: number) => {
        const res = await delAccount({id});
        if (res) {
            dataForm.getFieldsValue() ? await handleGetAccountSearch(dataForm.getFieldsValue().name) : await handleGetAccountList()
        }
    }

    // 处理账号批量删除
    const handleDelAllAccount = async (ids: any) => {
        const res = await delAllAccount({ids: JSON.stringify([ids])});
        if (res) {
            setIds([]);
            dataForm.getFieldsValue() ? await handleGetAccountSearch(dataForm.getFieldsValue().name) : await handleGetAccountList()
        }
    }

    // 查看详情账号
    const handleGetRegisterDetails = async (id: number) => {
        const res = await getAccountDetails({id});
        if (res) {
            // console.log(res);
            setFileList([{
                uid: '1',
                name: 'head.png',
                status: 'done',
                url: res.data[0].head,
            }])
            infoForm.setFieldsValue(res.data[0]);
        }
    }

    // 获取列表数据
    const handleGetAccountList = async () => {
        const res = await getAccountList({page: pagination.page, size: pagination.size});
        if (res) {
            setData(res.data)
            setPagination({...pagination, total: res.total});
        }
    }

    // 查询科室
    const handleGetAccountSearch = async (params: string) => {
        const res = await getAccountSearch({page: pagination.page, size: pagination.size, name: params})
        if (res) {
            setData(res.data)
            setPagination({...pagination, total: res.total});
        }
    }

    // 修改账号
    const handelEditAccount = async (params: DataType) => {
        const head = fileList[0]?.response?.header;
        params = {...params, head}
        const res = await editAccount(params)
        if (res) {
            await handleGetAccountList()
        }
        setFileList([])
    }


    useEffect((): void => {
        handleGetAccountList()
    }, []);

    // 提交查询表单
    const onFinish = async (values: any) => {
        await handleGetAccountSearch(values.name)
    };

    // 展示model
    const showModal = async (id: number, isEdit: boolean) => {
        await handleGetRegisterDetails(id)
        setIsEdit(isEdit)
        setIsModalOpen(true);

        if (isEdit) {
        }
    };

    // 确认按钮点击事件
    const handleOk = () => {
        isEdit ? handelEditAccount(infoForm.getFieldsValue()) : ''
        setIsModalOpen(false);
        setFileList([])
    };

    //  取消按钮点击事件
    const handleCancel = () => {
        setIsModalOpen(false);
        setFileList([])
    };


    /**
     * 删除功能点击事件
     * @param ids 要删除的id/ids
     * @param type 删除的类型：multiple-删除多个，single-删除一个
     */
    const handleDelClick = (ids: number[], type: string) => {
        confirm({
            title: '系统提示',
            icon: <ExclamationCircleOutlined/>,
            content: '您正在删除医务账号,此操作不可逆，确定删除吗？',
            okText: '确认删除',
            okType: 'danger',
            cancelText: '取消',
            width: 600,
            async onOk() {
                if (type === 'single') {
                    await handleDelAccount(ids[0])
                }
                if (type === 'multiple') {
                    await handleDelAllAccount(ids)
                }
            },
            onCancel() {
                message.error('用户取消删除')
            },
        });
    };


    // =========================================================
    // 预览状态
    const [previewOpen, setPreviewOpen] = useState(false);
    // 预览图像
    const [previewImage, setPreviewImage] = useState('');
    // 文件列表
    const [fileList, setFileList] = useState<UploadFile[]>([]);
    // 处理取消
    const handleImgCancel = () => setPreviewOpen(false);
    // 处理预览
    const handlePreview = async (file: UploadFile) => {
        if (!file.url && !file.preview) {
            file.preview = await getBase64(file.originFileObj as RcFile);
        }
        setPreviewImage(file.url || (file.preview as string));
        setPreviewOpen(true);
    };
    // 处理文件上传
    const handleChange: UploadProps['onChange'] = ({fileList: newFileList}) => {
        try {
            setFileList(newFileList.slice(-1)); // 只保留最后一个文件
            if (newFileList[0].status === 'done' && newFileList[0].response) {
                message.success('上传成功')
            }
        }catch {
            message.error('上传失败')
        }
    };

    const uploadButton = (
        <div>
            <PlusOutlined/>
        </div>
    );
    // ==========================================

    return (
        <div className={publicStyle.container}>

            {/*查询框*/}
            <div className={publicStyle.search}>
                <Form
                    layout={'inline'}
                    form={dataForm}
                    colon={false}
                    onFinish={onFinish}
                >
                    <Form.Item label="姓名" name="name">
                        <Input
                            prefix={<SearchOutlined/>}
                            placeholder="输入姓名进行查询"
                            className={publicStyle.searchInput}
                        />
                    </Form.Item>
                    <Form.Item>
                        <Button type="primary" htmlType="submit" icon={<SearchOutlined/>}>
                            查询
                        </Button>
                    </Form.Item>
                </Form>
                <Button type="default" onClick={() => handleDelClick(selectIds, 'multiple')}>删除选中</Button>
            </div>

            <div className={publicStyle.content}>
                <Table
                    rowKey={record => record.id}
                    rowSelection={{
                        type: 'checkbox',
                        ...rowSelection,
                    }}
                    size="small"
                    columns={columns}
                    dataSource={data}
                    pagination={{position: ['bottomLeft'], showSizeChanger: true, showQuickJumper: true}}
                />
            </div>

            {/*弹出框*/}
            <div className={publicStyle.modal}>
                <Modal
                    title={isEdit ? "编辑账号" : "医务账号详情"}
                    onOk={handleOk}
                    open={isModalOpen}
                    onCancel={handleCancel}
                    width={MODAL_WIDTH}
                >
                    <Form
                        {...formItemLayout}
                        colon={false}
                        form={infoForm}
                        layout={'horizontal'}
                        requiredMark={false}
                        initialValues={{
                            layout: 'horizontal'
                        }}
                    >
                        <Form.Item name="id" hidden>
                            <Input/>
                        </Form.Item>
                        <Form.Item label="医务账号" name="account">
                            <Input disabled placeholder="请输入账号名/手机号/邮箱"/>
                        </Form.Item>
                        <Form.Item label="权限" name="purview" rules={purviewRules}>
                            {
                                isEdit
                                    ?
                                    <Select
                                        options={options}
                                    />
                                    :
                                    <Input disabled/>
                            }
                        </Form.Item>
                        <Form.Item label="账号密码" name="password" rules={temporaryRules}>
                            <Input.Password disabled={!isEdit} placeholder="请输入密码"/>
                        </Form.Item>
                        <Form.Item label="身份证号" name="idcard">
                            <Input disabled placeholder="请输入该医务人员身份证号"/>
                        </Form.Item>
                        <Form.Item label="手机号" name="phone" rules={phoneRules}>
                            <Input disabled={!isEdit} placeholder="请输入手机号"/>
                        </Form.Item>
                        <Form.Item label="性别" name="sex">
                            <Input disabled/>
                        </Form.Item>
                        <Form.Item name="head" label='头像'>
                            {
                                isEdit
                                    ?
                                    (
                                        <>
                                            <Upload
                                                action="http://hjj.ink:21099/users/uploadheader"
                                                listType="picture-card"
                                                fileList={fileList}
                                                method="POST"
                                                onPreview={handlePreview}
                                                onChange={handleChange}
                                                maxCount={1}
                                            >
                                                {fileList.length >= 1 ? null : uploadButton}
                                            </Upload>
                                            <Modal open={previewOpen} title={''} footer={null}
                                                   onCancel={handleImgCancel}>
                                                <img alt="example" style={{width: '100%'}} src={previewImage}/>
                                            </Modal>
                                        </>
                                    )
                                    :
                                    <Image width={200} src={infoForm.getFieldValue('head')}/>
                            }
                        </Form.Item>
                    </Form>
                </Modal>
            </div>
        </div>
    )
}
